package com.jyniubi.core.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jyniubi.core.enums.BorrowerStatusEnum;
import com.jyniubi.core.enums.IntegralEnum;
import com.jyniubi.core.pojo.entity.*;
import com.jyniubi.core.mapper.BorrowerMapper;
import com.jyniubi.core.pojo.vo.ApprovalFormVO;
import com.jyniubi.core.pojo.vo.BorrowerDetailVO;
import com.jyniubi.core.pojo.vo.BorrowerVo;
import com.jyniubi.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author jyzhang
 * @since 2024-04-27
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private BorrowerAttachService borrowerAttachService;
    @Resource
    private DictService dictService;
    @Resource
    private UserIntegralService userIntegralService;

    @Override
    public void saveBorrower(BorrowerVo borrowerVo, Long userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVo,borrower);
        borrower.setUserId(userId);
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        this.save(borrower);
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoService.updateById(userInfo);

        String carUrl = borrowerVo.getCarUrl();
        String houseUrl = borrowerVo.getHouseUrl();
        String idcard1Url = borrowerVo.getIdcard1Url();
        String idcard2Url = borrowerVo.getIdcard2Url();

        BorrowerAttach borrowerAttach = new BorrowerAttach();
        borrowerAttach.setBorrowerId(borrower.getId());
        if (StringUtils.isNotBlank(carUrl)){
            borrowerAttach.setImageUrl(carUrl);
            borrowerAttach.setImageName("车");
            borrowerAttach.setImageType("car");
            borrowerAttachService.save(borrowerAttach);
        }
        if (StringUtils.isNotBlank(houseUrl)){
            borrowerAttach.setId(null);
            borrowerAttach.setImageUrl(carUrl);
            borrowerAttach.setImageName("房");
            borrowerAttach.setImageType("house");
            borrowerAttachService.save(borrowerAttach);
        }
        if (StringUtils.isNotBlank(idcard1Url)){
            borrowerAttach.setId(null);
            borrowerAttach.setImageUrl(idcard1Url);
            borrowerAttach.setImageName("身份证正面");
            borrowerAttach.setImageType("idcard1Url");
            borrowerAttachService.save(borrowerAttach);
        }
        if (StringUtils.isNotBlank(idcard2Url)){
            borrowerAttach.setId(null);
            borrowerAttach.setImageUrl(idcard2Url);
            borrowerAttach.setImageName("身份证国徽面");
            borrowerAttach.setImageType("idcard2Url");
            borrowerAttachService.save(borrowerAttach);
        }
    }

    @Override
    public Integer getBorrowerStatus(Long userId) {
        Borrower borrower = this.getOne(Wrappers.lambdaQuery(Borrower.class).eq(Borrower::getUserId, userId));
        if (borrower == null){
            return 0;
        }
        return borrower.getStatus();
    }

    @Override
    public Page<Borrower> getBorrowerList(Integer pageNum, Integer pageSize, String keyword) {
        Page<Borrower> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Borrower> queryWrapper = Wrappers.lambdaQuery(Borrower.class);
        if (StringUtil.isNotBlank(keyword)){
            queryWrapper.like(Borrower::getMobile,keyword)
                    .or().like(Borrower::getName,keyword)
                    .or().like(Borrower::getIdCard,keyword);
        }
        this.page(page,queryWrapper);
        return page;
    }

    @Override
    public BorrowerDetailVO getBorrowerDetailById(String id) {
        Borrower borrower = this.getById(id);
//        Borrower borrower = this.getOne(Wrappers.lambdaQuery(Borrower.class).eq(Borrower::getId, id));
        BorrowerDetailVO borrowerDetailVO = new BorrowerDetailVO();
        BeanUtils.copyProperties(borrower,borrowerDetailVO);
        borrowerDetailVO.setSex(borrower.getSex()==0 ?"女" :"男");
        borrowerDetailVO.setMarry(borrower.getMarry()?"是":"否");
        String status;
        switch (borrower.getStatus()){
            case 0:
                status = BorrowerStatusEnum.NO_AUTH.getMsg();
                break;
            case 1:
                status = BorrowerStatusEnum.AUTH_RUN.getMsg();
                break;
            case 2:
                status = BorrowerStatusEnum.AUTH_OK.getMsg();
                break;
            default:
                status = BorrowerStatusEnum.AUTH_FAIL.getMsg();
                break;
        }
        borrowerDetailVO.setStatus(status);
        List<BorrowerAttach> borrowerAttachList = borrowerAttachService.list(Wrappers.lambdaQuery(BorrowerAttach.class).eq(BorrowerAttach::getBorrowerId, id));
        borrowerDetailVO.setBorrowerAttaches(borrowerAttachList);
        Dict dict = dictService.getDictByDictCodeAndValue("returnSource", borrower.getReturnSource());
        borrowerDetailVO.setReturnSource(dict.getName());
        dict = dictService.getDictByDictCodeAndValue("industry", borrower.getReturnSource());
        borrowerDetailVO.setIndustry(dict.getName());
        dict = dictService.getDictByDictCodeAndValue("education", borrower.getReturnSource());
        borrowerDetailVO.setEducation(dict.getName());
        dict = dictService.getDictByDictCodeAndValue("income", borrower.getReturnSource());
        borrowerDetailVO.setIncome(dict.getName());
        dict = dictService.getDictByDictCodeAndValue("relation", borrower.getReturnSource());
        borrowerDetailVO.setContactsRelation(dict.getName());
        return borrowerDetailVO;
    }

    @Override
    public void approval(ApprovalFormVO approvalFormVO) {
        //获取审核状态 更新审核状态 borrower user_info
        Integer status = approvalFormVO.getStatus();
        Long borrowerId = approvalFormVO.getBorrowerId();
        Borrower borrower = new Borrower();
        borrower.setStatus(status);
        borrower.setId(borrowerId);
        this.updateById(borrower);
        borrower = this.getById(borrowerId);
        Long userId = borrower.getUserId();
        UserInfo userInfo = userInfoService.getById(userId);
        userInfo.setBorrowAuthStatus(status);
        //判断是否通过，如果通过再获取积分计算积分
        if (status.equals(BorrowerStatusEnum.AUTH_FAIL.getStatus())){
            userInfoService.updateById(userInfo);
            return;
        }
        //获取基本信息积分
        int total = 0;
        List<UserIntegral> userIntegrals = new ArrayList<>();
        UserIntegral userIntegral = new UserIntegral();
        total += approvalFormVO.getInfoIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(total);
        userIntegral.setContent("基本信息积分");
        userIntegrals.add(userIntegral);
        //获取身份信息积分
        if (approvalFormVO.getIsIdCardOk()){
            total += IntegralEnum.BORROWER_IDCARD.getIntegral();
            UserIntegral userIntegralCard = new UserIntegral();
            userIntegralCard.setUserId(userId);
            userIntegralCard.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegralCard.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
            userIntegrals.add(userIntegralCard);
        }
        //获取车辆信息积分
        if (approvalFormVO.getIsCarOk()){
            total += IntegralEnum.BORROWER_CAR.getIntegral();
            UserIntegral userIntegralCar = new UserIntegral();
            userIntegralCar.setUserId(userId);
            userIntegralCar.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegralCar.setContent(IntegralEnum.BORROWER_CAR.getMsg());
            userIntegrals.add(userIntegralCar);
        }
        //获取房产信息积分
        if (approvalFormVO.getIsHouseOk()){
            total += IntegralEnum.BORROWER_HOUSE.getIntegral();
            UserIntegral userIntegralHouse = new UserIntegral();
            userIntegralHouse.setUserId(userId);
            userIntegralHouse.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegralHouse.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
            userIntegrals.add(userIntegralHouse);
        }
        //然后原有的积分和现有的积分相加
        userInfo.setIntegral(userInfo.getIntegral()+total);
        //将最终积分更新到user_info表中
        userInfoService.updateById(userInfo);
        userIntegralService.saveBatch(userIntegrals);
    }
}
